package net.app.zoneland.platform.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.app.zoneland.common.core.vo.PageResult;
import net.app.zoneland.common.core.vo.Result;
import net.app.zoneland.domain.SysUser;
import net.app.zoneland.domain.SysUserRole;
import net.app.zoneland.dto.UserDTO;
import net.app.zoneland.platform.service.ISysRoleService;
import net.app.zoneland.platform.service.ISysUserRoleService;
import net.app.zoneland.platform.service.ISysUserService;
import net.app.zoneland.vo.UserVo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author LENOVO
 * @CreateTime 2020/12/20 12:50
 * @Version: 1.0
 */
@Api(tags = "用户接口")
@RestController
@RequestMapping("/users")
@Slf4j
@AllArgsConstructor
public class SysUserController {

    private final ISysUserService iSysUserService;

    private final ISysRoleService iSysRoleService;

    private final ISysUserRoleService iSysUserRoleService;

    @ApiOperation(value="用户列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value="页面",paramType = "query",dataType = "Integer"),
            @ApiImplicitParam(name="limit", value = "每页数量",paramType = "query",dataType = "Integer"),
            @ApiImplicitParam(name="user",value = "用户信息",paramType = "query",dataType = "SysUser")
    })
    @GetMapping
    public Result list(@RequestParam (value="page")Integer page, @RequestParam (value="limit")Integer limit, SysUser user){
        Page<SysUser> objectPage = new Page<>(page, limit);
        IPage<SysUser> result = iSysUserService.queryUserPage(objectPage, user);
        return PageResult.success(result.getRecords(), objectPage.getTotal());
    }

    @ApiOperation(value="用户名获取用户信息",httpMethod = "GET")
    @ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "query", dataType = "String")
    @GetMapping("/user/{username}")
    public Result<UserDTO> loadUserByUsername(@PathVariable String username){
        UserDTO userDTO = null;
        SysUser user = iSysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if(user!=null){
            userDTO=new UserDTO();
            // 复制属性
            BeanUtil.copyProperties(user,userDTO);
            List<Integer> roleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                    .eq(SysUserRole::getUserId, user.getId())
            ).stream().map(item -> item.getRoleId()).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(roleIds)) {
                List<Integer> roles = iSysRoleService.listByIds(roleIds).stream()
                        .map(role -> role.getId()).collect(Collectors.toList());
                userDTO.setRoles(roles);
            }
        }
        return Result.success(userDTO);
    }

    @ApiOperation(value="用户名获取用户信息",httpMethod = "GET")
    @ApiImplicitParam(name = "username", value = "用户名", required = true, paramType = "query", dataType = "String")
   // @Cacheable(value="users:query")  //自动根据方法生成缓存
    @GetMapping("/query/{username}")
    public Result<UserVo> queryUserInfo(@PathVariable String username){
        UserVo user = iSysUserService.findUserByUsername(username);
        return Result.success(user);
    }

    //@CacheEvict(value = "pullDownList",key = "#parameter.trim()")删除缓存
    @ApiOperation(value="用户ID获取用户信息",httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "用户名", required = true, paramType = "query", dataType = "Integer")
    @GetMapping("/queryById/{id}")
    public Result<SysUser> queryUserInfoById(@PathVariable Integer id){
        SysUser sysUser = iSysUserService.getById(id);
        return Result.success(sysUser);
    }

    @ApiOperation(value = "新增/更新用户", httpMethod = "POST")
    @ApiImplicitParam(name = "user", value = "实体JSON对象", required = true, paramType = "insert", dataType = "SysUser")
    @PostMapping
    @Transactional
    public Result add(SysUser user,String roleIds) {
        Result result = null;
        if(roleIds!=null && !"".equals(roleIds)){
            result=iSysUserService.saveUser(user,roleIds);
        }else {
            result = Result.error("角色不可为空");
        }
        return result;
    }

    @ApiOperation(value = "根据ID更新用户状态", httpMethod = "POST")
    @ApiImplicitParams({
       @ApiImplicitParam(name = "id", value = "用户唯一标识", required = true, paramType = "body", dataType = "Long"),
       @ApiImplicitParam(name = "ids", value = "用户唯一标识集合", required = true, paramType = "body", dataType = "Long")
    })
    @PostMapping("/upStatus/")
    public Result upStatus(String id,String del,String status){
        SysUser user=new SysUser();
        if(del!=null && "1".equals(del)){
            user.setDeleted(1);
        }

        if(status!=null && !"".equals(status)){
            Integer stat = Integer.parseInt(status);
            user.setStatus(stat);
        }
        if (id!=null && !"".equals(id)){
                long ide = Long.parseLong(id);
                    user.setId(ide);
            return iSysUserService.delUserById(user);
        }
       return Result.error("操作出错啦");
    }

    /**
     * 重置密码
     * @param username
     * @return
     */
    @PostMapping("/change/")
    public Result changePwd(String username){
        SysUser user=new SysUser();
        if(username!=null && !"".equals(username)){
                   user.setUsername(username);
            return iSysUserService.changePwd(user);
        }
        return Result.error("修改用户账号不可为空");
    }

    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(UserVo user){
        if(user==null || user.getUsername()==null || "".equals(user.getUsername())){
            return Result.error("账号不可为空");
        }
        Result result = iSysUserService.updateUser(user);
        return result;
    }
}
